#include "BarChart.hpp"
#include "cairomm/refptr.h"
#include "gtkmm/widget.h"

BarChart::BarChart(float maxval_,float minval_,int points_)
: minval(minval_)
, maxval(maxval_)
, allPoints(points_)
{
  oriData.resize(allPoints,0);
}

BarChart::~BarChart()
{

}

void BarChart::DrawCall(const Cairo::RefPtr<Cairo::Context>& cr,int width,int height,Gtk::Widget* widget)
{
  //绘制坐标系
  cr->save();
  int SourcePointX=20;
  int SourcePointY=height-20;
  cr->set_source_rgb(255,255,255);
  cr->set_line_width(3);
  cr->move_to(SourcePointX,SourcePointY);
  cr->line_to(20, 20);
  cr->line_to(15, 25);
  cr->move_to(20, 20);
  cr->line_to(25, 25);
  cr->move_to(SourcePointX, SourcePointY);
  cr->line_to(width-20, height-20);
  cr->line_to(width-25, height-25);
  cr->move_to(width-20, height-20);
  cr->line_to(width-25, height-15);
  cr->stroke();
  cr->restore();

  cr->save();
  //绘制折线 空间x:25 ~ width-25 y:25 ~ height-25
  float scale_item=(height-50)/(maxval-minval);
  int increase_val=(width-50)/(allPoints-1);
  // for(const auto & i : oriData)
  cr->set_source_rgb(255,0,0);
  cr->set_line_width(10);
  for(int j=0;j<allPoints;j++)
  {
    cr->move_to(25+j*increase_val, height-20);
    cr->line_to(25+j*increase_val, height-25-oriData[j]*scale_item);
  }
  cr->stroke();
  cr->restore();

  cr->save();
  cr->set_source_rgb(255, 255, 255);
  for(int j=0;j<allPoints;j++)
    DrawFont(cr, std::to_string(frameCounter>j ? frameCounter-j : 0), 25+j*increase_val, height-10, widget);
  //计算垂直标签
  int ylab_increate=(height-50)/5;
  for(int j=0;j<6;j++)
    DrawFont(cr, std::to_string((int)(minval+(maxval-minval)/5*j)), 10, height-25-j*ylab_increate,widget);
  cr->restore();
}

void BarChart::InputData(float point)
{
  oriData.push_front(point);
  oriData.pop_back();
  frameCounter++;
}

void BarChart::DrawFont(const Cairo::RefPtr<Cairo::Context>& cr,std::string str,int x,int y,Gtk::Widget* widget)
{
  Pango::FontDescription font;
  font.set_family("Monospace");
  auto layout = widget->create_pango_layout(str);
  layout->set_font_description(font);

  int text_width;
  int text_height;

  //get the text dimensions (it updates the variables -- by reference)
  layout->get_pixel_size(text_width, text_height);

  // Position the text in the middle
  cr->move_to(x-text_width/2, y-text_height/2);

  layout->show_in_cairo_context(cr);

}

void BarChart::ClearFrameCounter()
{
  frameCounter=0;
}
